package com.example.chengzhengwei.utils;

import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
    private static final String TAG = "FileUtils";
    private static final String CSV_FILENAME = "exported_data.csv";

    /**
     * 获取外部存储目录（包括U盘）
     */
    public static List<File> getExternalStorageDirectories(Context context) {
        List<File> storageDirs = new ArrayList<>();

        // 添加内置存储
        File primaryStorage = Environment.getExternalStorageDirectory();
        if (primaryStorage.exists() && primaryStorage.canWrite()) {
            storageDirs.add(primaryStorage);
        }

        // 添加可移动存储（U盘等）
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
            List<StorageVolume> storageVolumes = storageManager.getStorageVolumes();
            for (StorageVolume volume : storageVolumes) {
                if (!volume.isPrimary() && volume.isRemovable()) {
                    try {
                        File path = volume.getDirectory();
                        if (path != null && path.exists() && path.canWrite()) {
                            storageDirs.add(path);
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "Error getting storage volume path", e);
                    }
                }
            }
        } else {
            // 对于Android N以下版本，使用反射获取路径
            try {
                StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
                Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
                Method getVolumeList = storageManager.getClass().getMethod("getVolumeList");
                Method getPath = storageVolumeClazz.getMethod("getPath");
                Method isRemovable = storageVolumeClazz.getMethod("isRemovable");

                Object result = getVolumeList.invoke(storageManager);
                final int length = java.lang.reflect.Array.getLength(result);
                for (int i = 0; i < length; i++) {
                    Object storageVolumeElement = java.lang.reflect.Array.get(result, i);
                    String path = (String) getPath.invoke(storageVolumeElement);
                    boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);

                    if (removable) {
                        File file = new File(path);
                        if (file.exists() && file.canWrite()) {
                            storageDirs.add(file);
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Error getting removable storage paths", e);
            }
        }

        return storageDirs;
    }

    /**
     * 创建目录（如果不存在）
     */
    public static boolean createDirectoryIfNotExists(File directory) {
        if (directory == null) {
            return false;
        }

        if (!directory.exists()) {
            return directory.mkdirs();
        }

        return directory.isDirectory() && directory.canWrite();
    }

    /**
     * 将数据导出到CSV文件
     */
    public static boolean exportToCsv(List<String[]> data, File directory) {
        if (data == null || data.isEmpty() || directory == null) {
            return false;
        }

        // 确保目录存在
        if (!createDirectoryIfNotExists(directory)) {
            Log.e(TAG, "Failed to create directory: " + directory.getAbsolutePath());
            return false;
        }

        File csvFile = new File(directory, CSV_FILENAME);
        FileWriter writer = null;

        try {
            writer = new FileWriter(csvFile);

            // 写入数据
            for (String[] row : data) {
                StringBuilder line = new StringBuilder();
                for (int i = 0; i < row.length; i++) {
                    line.append(row[i]);
                    if (i < row.length - 1) {
                        line.append(",");
                    }
                }
                line.append("\n");
                writer.write(line.toString());
            }

            writer.flush();
            return true;
        } catch (IOException e) {
            Log.e(TAG, "Error writing CSV file", e);
            return false;
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    Log.e(TAG, "Error closing file writer", e);
                }
            }
        }
    }
}